<template>
  <div>
    <QueryForm v-model="filters" :query-form-config="queryFormConfig" @clear="clear" @handleQuery="getDataList">
      <template v-if="meta.indexOf('OnlineFoodEatGoodsStatisticsPort') > -1" #btns>
        <el-button v-preventReClick type="primary" @click="exportExcel">{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <el-table ref="tableRef" v-loading="listLoading" :data="list" element-loading-text="Loading" :span-method="objectSpanMethod" border show-summary :summary-method="getSummaries" fit :header-row-class-name="'table-header'" class="doumee-table">
      <el-table-column prop="ctName" align="center" :label="$t('message.ct')" min-width="200" show-overflow-tooltip />
      <el-table-column prop="goodsName" align="center" :label="$t('message.cpmc')" show-overflow-tooltip min-width="120" />
      <el-table-column prop="salePrice" align="center" :label="$t('message.xszr')" min-width="100" show-overflow-tooltip />
      <el-table-column prop="saleNum" align="center" :label="$t('message.xssl')" min-width="100" show-overflow-tooltip />
      <el-table-column prop="tkPrice" align="center" :label="$t('message.tkze')" min-width="100" show-overflow-tooltip />
      <el-table-column prop="tkNum" align="center" :label="$t('message.tksl')" min-width="100" show-overflow-tooltip />
      <el-table-column align="center" min-width="100" show-overflow-tooltip prop="subtotalMoney">
        <template slot="header">
          <el-tooltip effect="dark" placement="top" :content="$t('message.xjdxsjtk')">
            <div class="df_ac" style="justify-content: center;">{{ $t('message.xiaoji') }}<img style="width: 16px;" src="@/assets/icon/question.png"></div>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
import XLSX_STYLE from 'xlsx-style'
import { saveAs } from 'file-saver'
import { parseTime } from '@/utils/index'
import { eatGoodsStatistics, goodsRestaurantList2On } from '@/api'
import QueryForm from '@/components/QueryForm'
import dayjs from 'dayjs'
import { queryFormConfig } from './config'
export default {
  components: {
    QueryForm
  },
  data () {
    return {
      meta: [],
      queryFormConfig,
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      listLoading: false,
      showQk: false,
      filters: {},
      mergeList: [],
      mergeIndexList: [],
      ctList: []
    }
  },
  created () {
    this.meta = this.$route.meta.buttons || []
    this.init()
  },
  methods: {
    init () {
      let time = []
      const start = new Date()
      const end = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 29)
      end.setTime(end.getTime())
      time = [dayjs(start).format('YYYY-MM-DD'), dayjs(end).format('YYYY-MM-DD')]
      this.$set(this.filters, 'time', time)
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        var rowm = this.mergeList[rowIndex] - rowIndex
        var rowidx = this.mergeIndexList[rowIndex]
        if (rowIndex === rowidx) {
          return {
            rowspan: rowm,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
    },
    getLoading () {
      this.goodsRestaurantList()
      this.getDataList()
    },
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (index === 0) {
          sums[index] = this.$t('message.heji')
          return
        } else if (index === 1) {
          sums[index] = '-'
          return
        }
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = sums[index].toFixed(2)
        } else {
          sums[index] = '-'
        }
      })

      for (var key = 1; key <= sums.length; key++) {
        const number = sums[key]
        if (!isNaN(number)) {
          if (key === 3 || key === 5) {
            sums[key] = parseFloat(number).toFixed(0)
          } else {
            sums[key] = parseFloat(number).toFixed(2)
          }
        }
      }
      return sums
    },
    // 获取列表
    goodsRestaurantList () {
      goodsRestaurantList2On({ param: { venueId: sessionStorage.getItem('venueId'), type: 1, } })
        .then(res => {
          if (res.errorCode === '000000') {
            this.ctList = res.recordList || []
            this.queryFormConfig.formItems[0].options = res.recordList || []
          }
        })
        .catch(() => { })
    },
    getDataList () {
      const param = this.filters
      if (param.time && param.time.length > 0) {
        param.startTime = param.time[0]
        param.endTime = param.time[1]
      } else {
        param.startTime = ''
        param.endTime = ''
      }
      param.venueId = sessionStorage.getItem('venueId')
      param.type = '2'
      this.listLoading = true
      eatGoodsStatistics({ param }).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          const dataList = res.recordList
          const recordList = []
          const mergeList = []
          const mergeIndexList = []
          var colnum = 0
          var idx = 0
          dataList.forEach((e) => {
            colnum += e.items.length
            e.items.forEach((s) => {
              s['ctName'] = e['ctName']
              mergeList.push(colnum)
              recordList.push(s)
              mergeIndexList.push(idx)
            })
            idx += e.items.length
          })
          this.list = recordList
          this.mergeList = mergeList
          this.mergeIndexList = mergeIndexList
        }
      })
        .catch(() => { this.listLoading = false })
    },
    exportExcel () {
      const time = new Date().getTime()
      const filename = this.$t('message.dcxstj') + time + '.xlsx'
      const user = this.$store.state.app.user
      const param = this.filters
      var aoa = []
      if (param.time && param.time.length > 0) {
        aoa = [
          [this.$t('message.cxqsrq') + param.time[0] + ' 00:00:00' + this.$t('message.cxzjrq') + param.time[1] + ' 23:59:59']
        ]
      }
      const merges = []
      const mergeList = this.mergeList
      const mergeIndexList = this.mergeIndexList
      for (var s = 0; s < mergeList.length; ++s) {
        if (mergeList[s] - mergeIndexList[s] > 1) {
          merges.push({ e: { r: Number(mergeIndexList[s]) + 3, c: 0 }, s: { r: Number(mergeList[s]) + 2, c: 0 } })
        }
      }
      const workbook = XLSX.utils.book_new()
      var bottom = [
        [this.$t('message.dcsj') + parseTime(new Date())],
        [this.$t('message.dczh') + user.userName + ' -' + user.realName]
      ]
      // 创建工作簿
      var table_dom = this.$refs['tableRef'].$el
      const new_sheet = XLSX.utils.table_to_sheet(table_dom)
      const a = XLSX.utils.sheet_to_json(new_sheet, { header: 1 })
      aoa = aoa.concat(a).concat(bottom)
      const worksheet = XLSX.utils.json_to_sheet(aoa, { skipHeader: true })
      worksheet['!merges'] = merges
      const headerStyle = {
        font: {
          name: 'Arial'
        }
      }
      const contentStyle = {
        font: {
          name: 'Arial'
        }
      }
      const headerRange = XLSX.utils.decode_range(worksheet['!ref'])
      for (let col = headerRange.s.c; col <= headerRange.e.c; col++) {
        const headerCell = XLSX.utils.encode_cell({ r: headerRange.s.r, c: col })
        if (worksheet[headerCell]) {
          worksheet[headerCell].s = headerStyle
        }
      }

      // 将内容样式应用到 worksheet 对象中的所有单元格
      const contentRange = XLSX.utils.decode_range(worksheet['!ref'])
      for (let row = contentRange.s.r + 1; row <= contentRange.e.r; row++) {
        for (let col = contentRange.s.c; col <= contentRange.e.c; col++) {
          const contentCell = XLSX.utils.encode_cell({ r: row, c: col })
          if (worksheet[contentCell]) {
            worksheet[contentCell].s = contentStyle
          }
        }
      }
      XLSX.utils.book_append_sheet(workbook, worksheet, 'sheet1')
      const wbout = XLSX_STYLE.write(workbook, { bookType: 'xlsx', type: 'binary' })
      const blob = new Blob([this.s2ab(wbout)], { type: 'application/octet-stream' })
      saveAs(blob, filename)
    },
    s2ab (s) {
      const buf = new ArrayBuffer(s.length)
      const view = new Uint8Array(buf)
      for (let i = 0; i < s.length; i++) {
        view[i] = s.charCodeAt(i) & 0xFF
      }
      return buf
    },
    // 清空筛选项
    clear () {
      this.filters = {
        time: this.filters.time
      }
      this.getDataList()
    }
  }
}
</script>
